package org.zn.note.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.*;
import redis.clients.util.Pool;

import java.util.Set;

/**
 * Jedis
 * Jedis的实例不是线程安全的，不能在多个线程间共享同一个Jedis实例。一般通过JedisPool获取Jedis实例。
 */
public class JedisExample {

    public static void main(String[] args) {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        String host = "192.168.99.100";
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host);
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set("aaa", "bbb");
        }
    }

    /**
     * JedisSentinelPool （哨兵模式的Pool）
     * 1、和JedisPool类似，也是 extends Pool<Jedis>
     * 1、全参数构造方法：
     * JedisSentinelPool(
     * String masterName,
     * Set<String> sentinels,
     * final GenericObjectPoolConfig poolConfig,
     * final int connectionTimeout,
     * final int soTimeout,
     * final String password,
     * final int database,
     * final String clientName)
     * ① this.poolConfig\connectionTimeout\soTimeout\password\database\clientName = ...
     * ② HostAndPort master = initSentinels(sentinels, masterName); // 初始化哨兵，然后通过哨兵取得master
     * for(String sentinel : sentinels) {                   遍历这些哨兵，看哪个哨兵那里有masterName的节点信息
     * jedis = new Jedis(sentinel.host, sentinel.port)  连接哨兵
     * jedis.sentinelGetMasterAddrByName(masterName)    用masterName从哨兵那里取得这个主节点的ip:port(哨兵的注册中心作用)
     * }
     * ③ initPool(master); // 用master初始化pool
     */
    private static Pool jedisSentinelPool(String masterName, Set<String> sentinels) {
        return new JedisSentinelPool(masterName, sentinels);
    }

    /**
     * JedisCluster
     * 在Jedis里，JedisCluster支持redis集群操作。
     * 连上1个master，就能获取其他master的信息。
     */
    private static JedisCluster jedisCluster() {
        JedisCluster jedisCluster = new JedisCluster(HostAndPort.parseString(""));
        return jedisCluster;
    }

    private static class JedisPoolConfig extends GenericObjectPoolConfig {
        public JedisPoolConfig() {
            // defaults to make your life with connection pool easier :)
            setTestWhileIdle(true);
            setMinEvictableIdleTimeMillis(60000);
            setTimeBetweenEvictionRunsMillis(30000);
            setNumTestsPerEvictionRun(-1);
            setTestOnBorrow(true);
            setMaxTotal(5);
            setMaxIdle(5);
        }
    }
}
